/*
 * File Name：SentenceSpeechView.java
 * Copyright：Copyright 2008-2015 CiWong.Inc. All Rights Reserved.
 * Description： SentenceSpeechView.java
 * Modify By：res-jxliu
 * Modify Date：2015-1-23
 * Modify Type：Add
 */
package com.ciwong.epaper.widget.evaluate;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Scroller;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.evaluate.bean.Sentence;
import com.ciwong.epaper.modules.evaluate.bean.WordDetail;
import com.ciwong.epaper.modules.evaluate.ui.SpeechPlayController;
import com.ciwong.epaper.modules.evaluate.util.SpeechUtils;
import com.ciwong.epaper.util.DisplayUtils;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.PopWindowUtil;
import com.ciwong.epaper.widget.PlayStateView;
import com.ciwong.libs.oralevaluate.bean.EvaluateResult;
import com.ciwong.libs.oralevaluate.bean.Word;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.DeviceUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.utils.L;

import java.util.ArrayList;
import java.util.List;

/**
 * 句子跟读控件
 *
 * @author res-jxliu
 * @version ciwong v.1.0 2015-1-23
 * @since ciwong v.1.0
 */
public class SentenceSpeechView extends BaseRepFrameLayout {

    private final static String TAG = "SentenceSpeechView";

    private static final int DURATION = 400;

    private List<Sentence> mSentences;

    private TextView mTx_sentence_score;
    private ImageView tx_sentence_retry;

    private LinearLayout sentence_score_layout;
    private LinearLayout item_speech_ll_str;

    private int screenWdith = DeviceUtils.getScreenWdith();

    private int screenHeight = DeviceUtils.getScreenHeight();

    private ImageSize size = new ImageSize(screenWdith, screenHeight / 2);

    public LinearLayout getContainer() {
        return container;
    }

    private LinearLayout container;

    public ScrollView getScrollView() {
        return scrollView;
    }

    private ScrollView scrollView;

    private int scoreColor;

    private Scroller mScroller;

    private boolean isFillblank;

    private static final int COUNT = 2;// 播放状态显示的句子数量

    private ArrayList<RelativeLayout> stressList;

    private StressInterFace stressInterFace;
    //是否是手动模式
    private boolean isShouDongMode = false;
    //是否是考试模式
    private boolean mIsKaoShiMode = false;

    /**
     * 操作模式：逐句跟读、选段背诵、独立通读、单词跟读
     */
    protected int readMode = SpeechPlayController.LISTENER_MODE_ZHUJU;

    // 是否重读
    private boolean isStress = false;

    private boolean isAllComplete = false;

    public boolean isInSentenceAll() {
        return isInSentenceAll;
    }

    public void setInSentenceAll(boolean inSentenceAll) {
        isInSentenceAll = inSentenceAll;
    }

    private boolean isInSentenceAll = false;

    // 是否使用绘本模式
    public boolean mIsReadingMode = false;
    //是否手动模式
    private boolean mIsUnAutoMode = false;

    protected boolean isShowTranslate = false;

    public int getSumHei() {
        return sumHei;
    }

    public void setSumHei(int sumHei) {
        this.sumHei = sumHei;
    }

    public int getCount() {
        return countHigh;
    }

    public void setCount(int count) {
        this.countHigh = count;
    }

    public boolean ismIsReadingMode() {
        return mIsReadingMode;
    }

    public void setmIsReadingMode(boolean mIsReadingMode) {
        this.mIsReadingMode = mIsReadingMode;
    }

    public void setisShouDongMode(boolean mIsReadingMode) {
        this.isShouDongMode = mIsReadingMode;
    }

    public void setmIsUnAutoMode(boolean isUnAutoMode) {
        this.mIsUnAutoMode = isUnAutoMode;
    }

    public void setmIsKaoShiMode(boolean isKaoShiMode) {
        this.mIsKaoShiMode = isKaoShiMode;
    }


    public boolean isShowTranslate() {
        return isShowTranslate;
    }

    public void setShowTranslate(boolean showTranslate) {
        isShowTranslate = showTranslate;
    }

    public void setStress(boolean stress) {
        isStress = stress;
    }

    public void setStressInterFace(StressInterFace stressInterFace) {
        this.stressInterFace = stressInterFace;
    }

    public int getReadMode() {
        return readMode;
    }

    public void setReadMode(int readMode) {
        this.readMode = readMode;
    }

    public void setAllComplete(boolean allComplete) {
        isAllComplete = allComplete;
    }

    public SentenceSpeechView(Context context) {
        super(context);
        init();
    }

    public SentenceSpeechView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
        init();
    }

    public SentenceSpeechView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs);
        init();
    }

    private void init() {
        stressList = new ArrayList<>();
        container = new LinearLayout(getContext());
        scrollView = new ScrollView(getContext());
        scrollView.setVerticalScrollBarEnabled(false);
        scrollView.addView(container,
                new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT));
        addView(scrollView,
                new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT));
        container.setOrientation(LinearLayout.VERTICAL);
        container.setBackgroundResource(R.color.layer_bg_color);
        container.setPadding(0, DisplayUtils.dip2px(getContext(), 7), 0, 0);

        if (scoreColor == 0) {
            scoreColor = Color.LTGRAY;
        }
        mScroller = new Scroller(getContext());
    }

    private void init(AttributeSet attrs) {
        TypedArray a = getContext().obtainStyledAttributes(attrs,
                R.styleable.speech_text_view);
        scoreColor = a.getColor(R.styleable.speech_text_score_color,
                Color.LTGRAY);
        a.recycle();
    }

    /**
     * 获取当前句子控件
     */
    public SpeechTextView getCurrSpeechTextView(Sentence sentence) {
        View view = container.findViewWithTag(sentence);
        if (view == null) {
            return null;
        }
        return (SpeechTextView) view.findViewById(R.id.item_speech_tv);
    }

    /**
     * 重新置顶
     */
    public void toTop() {
        mScroller.startScroll(0, getScrollY(), 0, -getScrollY(), DURATION);
        invalidate();
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        if (mScroller.computeScrollOffset()) {
            int currY = mScroller.getCurrY();
            scrollView.scrollTo(0, currY);
            postInvalidate();
        }
    }

    /**
     * 设置段落数据
     *
     * @param sentences List<{@link Sentence}>
     */
    public void setSentences(List<Sentence> sentences, PlayStateView speech,
                             ImageView playIocn, long userId, boolean serviceExpired) {
        mSentences = sentences;
        initData(speech, playIocn, userId);
        addSentenceToView(serviceExpired);
    }

    /**
     * 是否是听说填空
     *
     * @param fillblank 是否是听说填空
     */
    public void setFillblank(boolean fillblank) {
        this.isFillblank = fillblank;
        Log.d("oubaoyu", "是否是听说填空:" + fillblank);
        if (mSentences == null) {
            return;
        }
        int len = container.getChildCount();
        for (int i = 0; i < len; i++) {
            View v = container.getChildAt(i).findViewById(R.id.item_speech_tv);
            if (v instanceof SpeechTextView) {
                SpeechTextView textView = (SpeechTextView) v;
                textView.setFillblank(fillblank);
            }
        }
    }

    /**
     * 是否显示中文翻译
     *
     * @param showTranslate 是否显示中文翻译
     * @param currIndex     当前播放
     */
    public void setShowTranslateMole(boolean showTranslate, final int currIndex) {
        this.isShowTranslate = showTranslate;
        if (mSentences == null) {
            return;
        }
        int len = container.getChildCount();
        for (int i = 0; i < len; i++) {
            final View itemView = container.getChildAt(i);
            View v = itemView.findViewById(R.id.tv_translate);
            if (v != null) {
                if (showTranslate) {
                    v.setVisibility(View.VISIBLE);
                } else {
                    v.setVisibility(View.GONE);
                }
            }
            if (i == currIndex) {
                itemView.getViewTreeObserver()
                        .addOnGlobalLayoutListener(
                                new ViewTreeObserver.OnGlobalLayoutListener() {
                                    @Override
                                    public void onGlobalLayout() {
                                        //itemView相对于父布局的坐标就得出来了
                                        mScroller.startScroll(0, 0, 0, itemView.getTop());
                                        itemView
                                                .getViewTreeObserver()
                                                .removeOnGlobalLayoutListener(
                                                        this);
                                    }
                                });
            }
        }
    }

    private void addSentenceToView(boolean serviceExpired) {
        addSentenceToView(0, false, false, false, serviceExpired);
    }

    /**
     * 添加view
     *
     * @param currIndex
     * @param isPlayState   是否是播放状态
     * @param isNeedReset   是否需要重置状态
     * @param isFromPlayAll 是否来自播放全文
     */
    public void addSentenceToView(final int currIndex, boolean isPlayState,
                                  boolean isNeedReset, boolean isFromPlayAll, boolean serviceExpired) {

        try {
            if (mSentences != null) {
                List<Sentence> sentencesList;
                // 一次显示几条
                int end = currIndex + COUNT;
                // 重读的时候只显示一条
                if (end > mSentences.size() || isStress || mIsReadingMode) {
                    end = currIndex + 1;
                }
                boolean isError = currIndex < 0 || currIndex > end
                        || end > mSentences.size();

                if (!mIsUnAutoMode) {
                    sentencesList = mSentences;
                } else if (isPlayState && !isError) {
                    sentencesList = mSentences.subList(currIndex, end);
                } else {
                    sentencesList = mSentences;
                }
                container.removeAllViews();
                stressList.clear();

                // lineList.clear();

                LayoutInflater inflater = LayoutInflater.from(getContext());
                for (int i = 0; i < sentencesList.size(); i++) {

                    final Sentence sentence = sentencesList.get(i);
                    final View itemView;
                    final SpeechTextView textView;
                    final TextView tvTranslate;
                    final ImageView unitPic;
                    boolean isResult = false;

                    if (isPlayState || isFromPlayAll || !isAllComplete) {
                        // 跟读页面过程
                        itemView = inflater.inflate(R.layout.speech_text_view,
                                null);
                        itemView.setBackgroundResource(R.color.white);
                        isResult = false;
                    } else {
                        // 跟读完成界面
                        itemView = inflater.inflate(
                                R.layout.speech_text_view_result, null);
                        mTx_sentence_score = (TextView) itemView
                                .findViewById(R.id.tx_sentence_score);

                        tx_sentence_retry = (ImageView) itemView.findViewById(R.id.tx_sentence_retry);
                        sentence_score_layout = (LinearLayout) itemView.findViewById(R.id.sentence_score_layout);
                        item_speech_ll_str = (LinearLayout) itemView.findViewById(R.id.item_speech_ll);

                        isResult = true;
                        if (i == 0 && itemView != null) {
                            final View firstView = itemView;
                            final TextView firstScoreTextView = (TextView) firstView
                                    .findViewById(R.id.tx_sentence_score);
                            final LinearLayout item_speech_ll = itemView.findViewById(R.id.item_speech_ll);
                            firstView.getViewTreeObserver()
                                    .addOnGlobalLayoutListener(
                                            new ViewTreeObserver.OnGlobalLayoutListener() {
                                                @Override
                                                public void onGlobalLayout() {
                                                    int hasShowCount = CWSys
                                                            .getSharedInt(
                                                                    EConstants.SHARE_KEY_REPEAT_TIPS
                                                                            + EApplication
                                                                            .getInstance()
                                                                            .getUserInfoBase()
                                                                            .getUserId(),
                                                                    0);
                                                    if (!(hasShowCount >= 3)) {
                                                        if (!mIsKaoShiMode) {
                                                            PopWindowUtil
                                                                    .showTipPopupWindow2(
                                                                            firstScoreTextView,
                                                                            new View.OnClickListener() {
                                                                                @Override
                                                                                public void onClick(
                                                                                        View v) {

                                                                                }
                                                                            });
                                                        }
                                                        hasShowCount++;
                                                        CWSys.setSharedInt(
                                                                EConstants.SHARE_KEY_REPEAT_TIPS
                                                                        + EApplication
                                                                        .getInstance()
                                                                        .getUserInfoBase()
                                                                        .getUserId(),
                                                                hasShowCount);
                                                    }
                                                    firstView
                                                            .getViewTreeObserver()
                                                            .removeOnGlobalLayoutListener(
                                                                    this);
                                                }
                                            });
                        }

                        final RelativeLayout stressRel = (RelativeLayout) itemView
                                .findViewById(R.id.stress_rel);
                        View score_level_line = itemView
                                .findViewById(R.id.score_level_line);

                        stressRel.findViewById(R.id.play_iocn)
                                .setOnClickListener(new OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        if (stressInterFace != null) {
                                            stressInterFace.stressIconRec(v,
                                                    stressRel);
                                        }
                                    }
                                });

                        stressRel.setVisibility(VISIBLE);
                        if (serviceExpired) {
                            mTx_sentence_score.setText(sentence.getScore() + "");
                            int score = sentence.getScore();
                            int color;
                            if (score < SpeechUtils.TOTAL_SCORE_1) {
                                color = R.color.score_red2;
                            } else if (score < SpeechUtils.TOTAL_SCORE_3) {
                                color = R.color.score_orange2;
                            } else {
                                color = R.color.score_green_word;
                            }

                            mTx_sentence_score
                                    .setTextColor(getResources().getColor(color));
                            score_level_line.setBackgroundResource(color);
                        } else {
                            mTx_sentence_score.setText("已提交");
                            mTx_sentence_score
                                    .setTextColor(getResources().getColor(R.color.color_light_green));
                            score_level_line.setBackgroundResource(R.color.color_light_green);

                        }
                        //点击重读
                        tx_sentence_retry.setVisibility(GONE);
                        mTx_sentence_score.setVisibility(VISIBLE);
                        mTx_sentence_score
                                .setOnClickListener(new OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        if (stressInterFace != null) {
                                            stressInterFace.stress(v,
                                                    stressRel);
                                        }
                                    }
                                });
                        if (!mIsKaoShiMode) {
                            item_speech_ll_str
                                    .setOnClickListener(new OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            if (stressInterFace != null) {
                                                stressInterFace.stress(v,
                                                        stressRel);
                                            }
                                        }
                                    });
                        }
//                        }
                        if (mIsKaoShiMode) {
                            //考试模式不显示分数
                            mTx_sentence_score.setVisibility(GONE);
                            tx_sentence_retry.setVisibility(GONE);
                        }
                        stressList.add(stressRel);
                    }
                    textView = itemView
                            .findViewById(R.id.item_speech_tv);
                    tvTranslate = itemView.findViewById(R.id.tv_translate);
                    unitPic = itemView.findViewById(R.id.unitPic);
                    if (isPlayState) {// 播放状态
                        if (mIsUnAutoMode) {
                            if (i == 0) { // 当前句子
                                if (!sentence.hasGrade() || isNeedReset) {
                                    sentence.setTextColor(getResources()
                                            .getColor(R.color.default_text_color));
                                    textView.setTextColor(getResources()
                                            .getColor(R.color.default_text_color));
                                }
                            } else {
                                // 下一个句子
                                if (!sentence.hasGrade()) {
                                    sentence.setTextColor(getResources()
                                            .getColor(R.color.repeat_read_gray));
                                    textView.setTextColor(getResources()
                                            .getColor(R.color.repeat_read_gray));
                                }
                            }
                        } else {

                            if (i == currIndex) { // 当前句子
                                if (!sentence.hasGrade() || isNeedReset) {
                                    sentence.setTextColor(getResources()
                                            .getColor(R.color.default_text_color));
                                    textView.setTextColor(getResources()
                                            .getColor(R.color.default_text_color));
                                }
                            } else {
                                // 下一个句子
                                if (!sentence.hasGrade()) {
                                    sentence.setTextColor(getResources()
                                            .getColor(R.color.repeat_read_gray));
                                    textView.setTextColor(getResources()
                                            .getColor(R.color.repeat_read_gray));
                                }
                            }
                        }

                    } else {// 暂停状态
                        if (!sentence.hasGrade() || isNeedReset) {
                            sentence.setTextColor(getResources()
                                    .getColor(R.color.default_text_color));
                        } else {
                            textView.setTextColor(getResources()
                                    .getColor(R.color.repeat_read_gray));

                        }
                    }
                    if (mIsKaoShiMode) {
                        sentence.setTextColor(getResources()
                                .getColor(R.color.default_text_color));
                    }
                    textView.setFillblank(isFillblank);
                    if (mIsUnAutoMode) {
                        textView.setSentence(sentence, null, isFromPlayAll,
                                getResources().getColor(
                                        i == 0 ? R.color.default_text_color
                                                : R.color.repeat_read_gray),
                                true);
                    } else {
                        textView.setSentence(sentence, null, isFromPlayAll,
                                getResources().getColor(
                                        i == currIndex ? R.color.default_text_color
                                                : R.color.repeat_read_gray),
                                true);
                    }
                    itemView.setTag(sentence);

                    Log.e(TAG, "addSentenceToView: 用于播放全文 before");
                    // 翻译有字段并且在播放全文时才显示
                    if (tvTranslate != null) {
                        if (!TextUtils.isEmpty(sentence.getTranslate())) {
                            tvTranslate.setText(sentence.getTranslate());
                            if (isShowTranslate) {
                                tvTranslate.setVisibility(VISIBLE);
                            } else {
                                tvTranslate.setVisibility(GONE);
                            }
                        } else {
                            tvTranslate.setVisibility(GONE);
                        }
                    }
                    if (mIsReadingMode) {
                        if (textView != null) {
                            textView.setGravity(Gravity.LEFT);
                        }
                        if (unitPic != null) {
                            unitPic.setVisibility(VISIBLE);
                            unitPic.setMinimumHeight(screenHeight / 2);
                            if (sentence.getImgUrl() != null) {
                                String url = ESystem
                                        .formatPath(sentence.getImgUrl());
                                if (url == null) {
                                    url = "";
                                }
                                ImageLoader.getInstance().loadImage(url, size,
                                        new ImageLoadingListener() {
                                            @Override
                                            public void onLoadingStarted(
                                                    String s, View view) {

                                            }

                                            @Override
                                            public void onLoadingFailed(
                                                    String s, View view,
                                                    FailReason failReason) {

                                            }

                                            @Override
                                            public void onLoadingComplete(
                                                    String s, View view,
                                                    Bitmap bitmap) {
                                                unitPic.setImageBitmap(bitmap);
                                            }

                                            @Override
                                            public void onLoadingCancelled(
                                                    String s, View view) {

                                            }
                                        });
                            }
                        }
                    } else {
                        if (unitPic != null) {
                            unitPic.setVisibility(GONE);
                        }
                        if (textView != null) {
                            textView.setGravity(Gravity.LEFT);
                        }
                    }
                    try {
                        int padding = DisplayUtils.dip2px(getContext(), 15);
                        // 结果页可能为null
                        if (tvTranslate != null
                                && tvTranslate.getVisibility() == VISIBLE) {
                            int paddingBttom = DisplayUtils.dip2px(getContext(),
                                    5);
                            textView.setPadding(padding, padding, padding,
                                    paddingBttom);
                        } else {
                            textView.setPadding(padding, padding, padding,
                                    padding);
                        }
                    } catch (Exception e) {

                    }
                    itemView.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (stressInterFace != null) {
                            }
                        }
                    });
                    container.addView(itemView);
                }
            }
        } catch (InflateException e) {

        }
    }

    /**
     * 前面控件的总高度
     */
    int sumHei = 0;
    /**
     * 正在播放的控件高度
     */
    int countHigh = 0;

    /**
     * 用于播放全文
     *
     * @param currIndex
     * @param isPlayState
     */
    public void addSentenceToView(int currIndex, boolean isPlayState) {
        Log.e(TAG, "addSentenceToView: 用于播放全文");
        if (mSentences != null) {
            if (currIndex >= mSentences.size()) {
                currIndex = 0;
                sumHei = 0;
                tempList.clear();
                // mScroller.startScroll(0, 0, 0, sumHei);
                // invalidate();
                return;
            }
            if (container.getChildCount() > 0) {
                // 控件总高度
                for (int i = 0; i < mSentences.size(); i++) {
                    final View itemView = container.getChildAt(i);
                    if (container == null || itemView == null) {
                        return;
                    }
                    SpeechTextView textView = container
                            .getChildAt(i).findViewById(R.id.item_speech_tv);
                    TextView tvTranslate = itemView
                            .findViewById(R.id.tv_translate);
                    final ImageView unitPic = itemView
                            .findViewById(R.id.unitPic);
                    if (textView == null) {
                        return;
                    }

                    textView.setTextColor(
                            getResources().getColor(R.color.repeat_read_gray));
                    String sentense = mSentences.get(i).getText()
                            .replace("{", "").replace("}", "");

                    if (i < currIndex) {
                        textView.setSentence(mSentences.get(i), null, false,
                                getResources().getColor(
                                        i == currIndex ? R.color.default_text_color
                                                : R.color.repeat_read_gray),
                                true);
                    } else {
                        if (readMode == SpeechPlayController.LISTENER_MODE_XUANDUAN) {
                            textView.setSentence(mSentences.get(i), null, false,
                                    getResources().getColor(
                                            i == currIndex ? R.color.default_text_color
                                                    : R.color.repeat_read_gray),
                                    true);
                        } else {
                            textView.setText(sentense);
                        }
                    }

                    if (tvTranslate != null && !TextUtils
                            .isEmpty(mSentences.get(i).getTranslate())) {
                        tvTranslate.setTextColor(getResources()
                                .getColor(R.color.repeat_read_gray));
                        tvTranslate.setText(mSentences.get(i).getTranslate());
                        if (isShowTranslate) {
                            tvTranslate.setVisibility(VISIBLE);
                        } else {
                            tvTranslate.setVisibility(GONE);
                        }
                    }

                    if (unitPic != null && unitPic.getVisibility() == VISIBLE) {
                        if (mSentences.get(i).getImgUrl() != null) {
                            String url = ESystem
                                    .formatPath(mSentences.get(i).getImgUrl());
                            if (url == null) {
                                url = "";
                            }
                            ImageSize size = new ImageSize(
                                    DeviceUtils.getScreenWdith(),
                                    R.dimen.word_pic_height);
                            ImageLoader.getInstance().loadImage(url, size,
                                    new ImageLoadingListener() {
                                        @Override
                                        public void onLoadingStarted(String s,
                                                                     View view) {

                                        }

                                        @Override
                                        public void onLoadingFailed(String s,
                                                                    View view,
                                                                    FailReason failReason) {

                                        }

                                        @Override
                                        public void onLoadingComplete(String s,
                                                                      View view, Bitmap bitmap) {
                                            unitPic.setImageBitmap(bitmap);
                                        }

                                        @Override
                                        public void onLoadingCancelled(String s,
                                                                       View view) {

                                        }
                                    });
                        }
                    }
                    try {
                        int padding = DisplayUtils.dip2px(getContext(), 15);
                        if (tvTranslate != null
                                && tvTranslate.getVisibility() == VISIBLE) {
                            int paddingBttom = DisplayUtils.dip2px(getContext(),
                                    5);
                            textView.setPadding(padding, padding, padding,
                                    paddingBttom);
                        } else {
                            textView.setPadding(padding, padding, padding,
                                    padding);
                        }
                    } catch (Exception e) {

                    }

                    if (i == currIndex) {
                        // 如果是当前
                        textView = itemView
                                .findViewById(R.id.item_speech_tv);
                        textView.setTextColor(getResources()
                                .getColor(R.color.default_text_color));

                        if (tvTranslate != null
                                && tvTranslate.getVisibility() == VISIBLE) {
                            tvTranslate.setTextColor(getResources()
                                    .getColor(R.color.default_text_color));
                        }

                        if (isPlayState) {
//                            mScroller.startScroll(0, 0, 0, sumHei);
                            itemView.getViewTreeObserver()
                                    .addOnGlobalLayoutListener(
                                            new ViewTreeObserver.OnGlobalLayoutListener() {
                                                @Override
                                                public void onGlobalLayout() {
                                                    //itemView相对于父布局的坐标就得出来了
                                                    mScroller.startScroll(0, 0, 0, itemView.getTop());
                                                    itemView
                                                            .getViewTreeObserver()
                                                            .removeOnGlobalLayoutListener(
                                                                    this);
                                                }
                                            });
                            countHigh = getSenItemHei(itemView);
                            if (!isInSentenceAll) {
                                if (countHigh == 0) {
                                    countHigh = 178;
                                }
                            }
                            if (mSentences.size() > currIndex) {
                                mSentences.get(currIndex).setCount(countHigh);
                            }
                            invalidate();
                        }
                    }
                }
            }
        }
    }


    /**
     * 播放下一个的回调
     *
     * @param currentIndex
     * @param mIsUnAutoMode 是否手动模式 true为手动
     */
    public void nextCount(int currentIndex, boolean mIsUnAutoMode) {
        if (mIsUnAutoMode) {
            if (mSentences.size() > currentIndex) {
                countHigh = mSentences.get(currentIndex).getCount();
            }
        }
        sumHei = sumHei + countHigh;
    }

    //上一步的时候调用
    public void previousCount(int index) {
        if (mSentences.size() > index) {
            int currcountHigh = mSentences.get(index).getCount();
            countHigh = currcountHigh;
            sumHei = sumHei - currcountHigh;
        }
    }

    /**
     * 暂停调用
     */
    public void stopCount() {
        if (tempList.size() > 0) {
            tempList.remove(tempList.size() - 1);
        }
    }

    private List<View> tempList = new ArrayList<View>();

    private int getSenItemHei(View v) {
        for (int i = 0; i < tempList.size(); i++) {
            if (tempList.get(i) == v) {
                return 0;
            }
        }
        tempList.add(v);
        return v.getHeight();
    }

    /**
     * 设置评分结果
     *
     * @param er       评分后的单词
     * @param sentence 句子
     * @param isFill   true=选段背诵
     */
    public void showResult(EvaluateResult er, Sentence sentence, boolean isFill, boolean serviceExpired) {
        if (serviceExpired) {
            sentence.setHasGrade(true);
            sentence.setScore((int) er.getScore());
            sentence.setTextColor(
                    getResources().getColor(R.color.repeat_read_gray));
            List<Word> gradeWords = er.getWords();
            List<WordDetail> words = sentence.getWordDetails();

            int index = 0;
            String sample = SpeechUtils.replaceAsSpace(er.getSample());
            String sentenceText = SpeechUtils.replaceAsSpace(
                    SpeechUtils.replaceEvaluateText(sentence.getText()));
            int gradeWordIndexStart = 0;
            int gradeWordIndex = 0;
            for (int i = 0; i < gradeWords.size(); i++) {
                Word gradeWord = gradeWords.get(i);
                String gradeWordText = gradeWord.getText().trim();
                // 修改与2016/09/29 对单词也要做字符过滤 不然去子字符串的时候会报错
                gradeWordText = SpeechUtils.replaceAsSpace(gradeWordText);

                if (gradeWordIndex != -1) {
                    gradeWordIndex = sample.indexOf(gradeWordText, gradeWordIndex);
                    // 说明去子集的时候报错了 目前正对CJ3这个单词做特殊处理 云知声对于这样的单词做为2个单词处理 所以要索引要减去1
                    if (gradeWordIndex == -1) {
                        gradeWordIndex -= 1;
                        gradeWordIndex = sample.indexOf(gradeWordText,
                                gradeWordIndex);
                    }
                    gradeWordIndexStart = gradeWordIndex;
                }
                if (gradeWordIndex != -1) {
                    gradeWordIndex += gradeWordText.length() + 1;
                }
                index = 0;
                int wIndexStart = 0;
                int wIndex = 0;
                while (true) {
                    if (index >= words.size()) {
                        break;
                    }
                    WordDetail w = words.get(index);
                    String wStr = w.getText().trim();
                    if (wIndex != -1) {
                        wIndex = sentenceText.indexOf(wStr, wIndex);
                        wIndexStart = wIndex;
                    }
                    if (wIndex != -1) {
                        wIndex += wStr.length() + 1;
                    }
                    // 匹配规则修改2016/09/29 开始位置一样 或者结束位置一样 by young
                    // 目前正对CJ3这个单词做特殊处理 云知声对于这样的单词做为2个单词处理
                    boolean isMatch = (gradeWordIndex != -1 && wIndex != -1
                            && gradeWordIndex == wIndex)
                            || (gradeWordIndex != -1 && wIndex != -1
                            && gradeWordIndexStart == wIndexStart);
                    // 匹配规则修改2016/09/29 相等或者是子集都表示相同by young
                    // 目前正对CJ3这个单词做特殊处理 云知声对于这样的单词做为2个单词处理 所以反过来包括也可以
                    if ((isMatch && SpeechUtils.replace(w.getText())
                            .equals(gradeWord.getText()))
                            || (isMatch && SpeechUtils.replace(w.getText())
                            .contains(wStr))
                            || (isMatch && wStr
                            .contains(SpeechUtils.replace(w.getText())))) {
                        w.setScore(gradeWord.getScore());
                        int color;
                        if (gradeWord.getScore() < SpeechUtils.SCORE_6) {
                            color = R.color.me_item_name_sub_txt_color;

                        } else if (gradeWord.getScore() < SpeechUtils.ONE_SCORE_2) {
                            color = R.color.score_red;

                        } else if (gradeWord.getScore() < SpeechUtils.ONE_SCORE_4) {
                            color = R.color.score_yellow;

                        } else {
                            color = R.color.score_green_word;

                        }
                    /*if (!mIsReadingMode) {
                        //考试模式结果不染色
                        color = R.color.default_text_color;
                    }*/
                        w.setColor(getResources().getColor(color));
                        index++;
                        continue;
                    }
                    index++;

                }
            }

            SpeechTextView textView = (SpeechTextView) findViewWithTag(sentence)
                    .findViewById(R.id.item_speech_tv);
            // textView.setScoreColor(SpeechColor.COLOR_GRAY);
            textView.setScoreTextSize(
                    getContext().getResources().getDimensionPixelSize(
                            R.dimen.speech_text_view_result_text_size));
            textView.setFillblank(isFill);
            textView.setSentence(sentence, false);
            textView.setTextColor(
                    getResources().getColor(R.color.repeat_read_gray));

            // 将人名设置为黑色
            try {
                int[] indexArray = SpeechUtils
                        .isMatchPersonName(sentence.getText());
                if (indexArray != null) {
                    ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(
                            getResources().getColor(R.color.default_text_color));
                    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(
                            textView.getText());
                    spannableStringBuilder.setSpan(foregroundColorSpan,
                            indexArray[0], indexArray[1] - 1,
                            Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                    // 将翻译设为黑色。
                    int[] translateArray = SpeechUtils
                            .isMatchPersonName(sentence.getText());
                    if (translateArray != null) {
                        spannableStringBuilder.setSpan(foregroundColorSpan,
                                translateArray[0] - 2, translateArray[1] - 1,
                                Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                    }

                    textView.setText(spannableStringBuilder);
                } else {
                    int[] translateArray = SpeechUtils
                            .isMatchPersonName(sentence.getText());
                    if (translateArray != null) {
                        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(
                                getResources()
                                        .getColor(R.color.default_text_color));
                        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(
                                textView.getText());
                        spannableStringBuilder.setSpan(foregroundColorSpan,
                                translateArray[0], translateArray[1],
                                Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                        textView.setText(spannableStringBuilder);
                    }
                }
            } catch (Exception e) {
                e.getStackTrace();
            }
        } else {
            sentence.setHasGrade(true);
            sentence.setScore((int) er.getScore());
            sentence.setTextColor(
                    getResources().getColor(R.color.black));
            SpeechTextView textView = findViewWithTag(sentence)
                    .findViewById(R.id.item_speech_tv);
            textView.setScoreTextSize(
                    getContext().getResources().getDimensionPixelSize(
                            R.dimen.speech_text_view_result_text_size));
            textView.setFillblank(isFill);
            textView.setSentence(sentence, false);
            textView.setTextColor(
                    getResources().getColor(R.color.black));
        }
    }

    public int getIndexByView(RelativeLayout relativeLayout) {
        if (stressList != null) {
            return stressList.indexOf(relativeLayout);
        } else {
            return 0;
        }
    }

    public void showOrCloseStress(int index) {

    }

    public void showLine() {
    }

    /**
     * 重读的接口定义
     */
    public interface StressInterFace {
        void stress(View v, RelativeLayout relativeLayout);

        void stressItemClick(View v, RelativeLayout relativeLayout);

        void stressIconRec(View v, RelativeLayout relativeLayout);

        void scoreReTry(boolean isLastOne, Sentence sentence);

    }
}
